<?php

namespace App\Http\Controllers;

use App\Models\Goods;
use App\Models\Order;
use App\Models\Org;
use App\Models\Team;
use App\Models\WechatTempMsg;
use App\User;
use Carbon\Carbon;
use EasyWeChat\Core\Exception;
use Hashids\Hashids;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Facades\Excel;
use SimpleSoftwareIO\QrCode\Facades\QrCode;


class TeamController extends Controller
{
    public function index(Request $request) {
        $user = $request->user();
        $perPage = $request->get('perPage', 10);
        $query = Team::with('org')->with('parentTeam');
        $query->where('verify_status', '=', 1);
        $query->where('in_blacklist', '=', 0);

        if ($user->type == 4 || $user->type == 5) {
            if ($request->has('org_id')) {
                $query->where('org_id', '=', $request->get('org_id'));
            }

            if ($request->has('parent_id') && intval($request->get('parent_id'))) {
                $team = Team::find($request->get('parent_id'));
                $teamIds = array_map(function($item) {
                    return $item['id'];
                }, Team::whereDescendantOf($team)->select('id')->where('org_id',$team->org_id)->get()->toArray());

                array_unshift($teamIds, $team->id);

                $query->whereIn('parent_id', $teamIds);
            } else {
                // $query->whereNull('parent_id');
            }
        } else if ($user->type == 3) {
            $query->where('org_id', '=', $user->org_id);

            if ($request->has('parent_id') && intval($request->get('parent_id'))) {
                $team = Team::find($request->get('parent_id'));
                $teamIds = array_map(function($item) {
                    return $item['id'];
                }, Team::whereDescendantOf($team)->select('id')->where('org_id',$team->org_id)->get()->toArray());

                array_unshift($teamIds, $team->id);

                $query->whereIn('parent_id', $teamIds);
            } else {
                // $query->whereNull('parent_id');
            }
        } else if ($user->type == 2) {
            $team = $user->team;

            $teamIds = array_map(function($item) {
                return $item['id'];
            }, Team::whereDescendantOrSelf($team)->select('id')->where('org_id',$user->team->org_id)->get()->toArray());

//            array_unshift($teamIds, $team->id);
//            dd($teamIds);
            $query->whereIn('parent_id', $teamIds);
//            $query->where('org_id', '=', $user->team->org_id);
//
//             必须是所属团队的下级
//            $query->where('_lft', '>=', $user->team->_lft);
//            $query->where('_rgt', '<=', $user->team->_rgt);
        } else {
            throw new \Exception('权限不足');
        }

        if ($request->has('keywords')) {
            $query->where(function($query) use ($request) {
                $query->orWhere('name', 'like', '%'.$request->get('keywords').'%');
                $query->orWhere('contact_name', 'like', '%'.$request->get('keywords').'%');
                $query->orWhere('legal_person', 'like', '%'.$request->get('keywords').'%');
            });
        }

        if ($request->has('stars_verify_status')) {
            $query->where('stars_verify_status', '=', $request->get('stars_verify_status'));
        }

        if ($request->has('stars')) {
            $query->where('stars', '=', $request->get('stars'));
        }



        if ($request->has('type')) {
            $query->where('type', '=', $request->get('type'));
        }

        if ($request->has('service_target')) {
//            $query->where('service_target', '=', $request->get('service_target'));
            $query->whereRaw('FIND_IN_SET( \''.$request->get('service_target') .'\', service_target)');
        }

        if($request->get('orderBy') && $request->get('orderDir'))
        {
            $query->orderBy($request->get('orderBy'), $request->get('orderDir'));
        }

        if ($user->type == 5) {
            $org_list = $user->platform->org_list;
            $query = $query->whereIn('org_id', $org_list);
//            $info['data'] = $query->get()->toArray();
//            $info['total'] = count($org_list);
        } else {
//            $info = $query->paginate($perPage)->toArray();
        }

        $asExcel = $request->get("asExcel", false);
        $info = null;
        if($asExcel){
            // 保持和分页的结构一致，设置data=>{}
            $tmp = $query->get()->toArray();
            $info = array(
                'data' => $tmp
            );
        }else {
            $info = $query->paginate($perPage)->toArray();
        }

        $ids = array_map(function($item) {
            return $item['id'];
        }, $info['data']);

        if (count($ids)) {
            $projects = DB::table('project')
                ->select(DB::raw('count(*) as project_count, team_id'))
                ->whereIn('team_id', $ids)
                ->where('verify_status', '=', 1)
                ->groupBy('team_id')
                ->get();

            $projectMap = [];
            foreach ($projects as $project) {
                $projectMap[$project->team_id] = $project;
            }


            $people = DB::table('user_team')
                ->select(DB::raw('count(*) as people_count, team_id'))
                ->whereIn('team_id', $ids)
                ->groupBy('team_id')
            ->get();

            $peopleMap = [];
            foreach ($people as $people) {
                $peopleMap[$people->team_id] = $people;
            }

            $subTeamCountMap = [];
            $subTeamCounts = DB::select( DB::raw("SELECT `team1`.`id`, COUNT(`team2`.`id`) as `sub_team_count` FROM `team` AS `team1` LEFT JOIN `team` AS `team2` ON `team1`.`org_id` = `team2`.`org_id` AND `team1`.`_lft` < `team2`.`_lft` AND `team1`.`_rgt` > `team2`.`_rgt` AND `team2`.`verify_status` = 1 WHERE `team1`.`id` IN (".join(",", $ids).") GROUP BY `team1`.`id`"));
            foreach ($subTeamCounts as $subTeamCount) {
                $subTeamCountMap[$subTeamCount->id] = $subTeamCount;
            }

            // print_r($subTeamCountMap);exit;

            foreach ($info['data'] as &$item) {
                if (isset($projectMap[$item['id']])) {
                    $item['project_count'] = $projectMap[$item['id']]->project_count;
                } else {
                    $item['project_count'] = 0;
                }

                if (isset($peopleMap[$item['id']])) {
                    $item['people_count'] = $peopleMap[$item['id']]->people_count;
                } else {
                    $item['people_count'] = 0;
                }

                if (isset($subTeamCountMap[$item['id']])) {
                    $item['sub_team_count'] = $subTeamCountMap[$item['id']]->sub_team_count;
                } else {
                    $item['sub_team_count'] = 0;
                }
            }
        }

//        print_r(headers_sent()==0);
        if ($asExcel){
            $excel = Excel::create(time(),function($excel) use ($info){

                $excel->sheet('volunteer', function($sheet) use ($info){

                    $sheet->appendRow(1, array(
                        '团队ID', '所属机构', '团队名称', '口号', '团队简介', '团队Logo','团队类型', '服务对象', '团队人数', '团队项目数', '志愿者人数', '志愿时长', '编号', '上级团队ID', '联系人',
                        '联系人电话', '联系人邮箱', '团队地址', '团队法人姓名','团队法人身份证号', '团队法人联系电话',
                        '资格证书', '团队照片',  '累计时长', '创建时间'
                    ));
//                    print_r($info['data']);

                    for ($i = 0;$i<count($info['data']);$i++){
                        $tmp = $info['data'][$i];
//                        print_r($tmp);
                        $sheet->appendRow($i+2,array(
                            $tmp["id"], $tmp["org_id"], $tmp["name"], $tmp["slogan"], $tmp['abstract'], $tmp['logo'], $tmp['type'],
                            $tmp['service_target'],$tmp['team_size'],$tmp['project_count'], $tmp['people_count'], $tmp['reward_time'],
                            $tmp['identifier'], $tmp['parent_id'], $tmp['contact_name'], $tmp['contact_phone'], $tmp['contact_email'],null,
                            $tmp['legal_person'], $tmp['legal_person_id'], $tmp['legal_person_phone'], $tmp['certificate_photo'],
                            $tmp['team_photo'], $tmp['reward_time'], $tmp['created_at']));
                    }
                });
            })->export('xls');
//            return response($excel->export('xls'), 200, [
//                'Content-type'=>'application/vnd.ms-excel; charset=UTF-8',
//                'Content-Disposition' => 'attachment; filename="' .time(). '.xls"',
//                'Expires'             => 'Mon, 26 Jul 1997 05:00:00 GMT', // Date in the past
//                'Last-Modified'       => Carbon::now()->format('D, d M Y H:i:s'),
//                'Cache-Control'       => 'cache, must-revalidate',
//                'Pragma'              => 'public',
//            ]);
//            return null;
        }else {

            return $this->returnJSON([
                'count' => $info['total'],
                'rows' => $info['data']
            ]);
        }
    }

    public function show($id) {
        $node = Team::findOrFail($id);
        $data = $node->toArray();

        if (isset($data['user_id'])) {
            $user = User::findOrFail($data['user_id']);
            $data['username'] = $user->username;
            $data['email'] = $user->email;
        }

        return $this->returnJSON($data, 0, 'ok');
    }

    public function store(Request $request) {
        $user = $request->user();
        $this->validate($request, [
            'org_id' => $user->type == 4 || $user->type == 5 ? 'required' : '',
            'name' => ['required', 'max:32', Rule::unique('team')->where(function($query) use ($user){
                if($user->type == 4 || $user->type == 5)
                {
                    $orgId = request()->input('org_id');
                }elseif($user->type == 3)
                {
                    $orgId = $user->org_id;
                } else {
                    $orgId = $user->team->org_id;
                }
                $query->where('org_id', $orgId);
            })],
            'type' => 'required|max:32',
            'service_target' => 'required|max:32',
            'contact_name' => 'required|max:32',
            'contact_phone' => 'required|max:32',
            'contact_email' => 'required|max:255|email',
            'address' => 'required',
//            'legal_person' => 'required|max:12',
//            'legal_person_id' => 'required|max:18',
//            'legal_person_phone' => 'required|max:32',
            'abstract' => 'required',
            'username' => 'required|unique:user|max:64',
            'pwd' => 'required|max:64',
            'slogan' => 'max:20'
        ]);

        $node = new Team();
        $data = $request->only([
            'org_id',
            'logo',
            'name',
            'type',
            'service_target',
            'auth_create_goods',
            'contact_name',
            'contact_phone',
            'contact_email',
            'contact_addr',
//            'legal_person',
//            'legal_person_id',
//            'legal_person_phone',
            'certificate_photo',
            'team_photo',
            'abstract',
            'username',
            'pwd',
            'acl',
            'parent_id',
            'address',
            'slogan'
        ]);

        if ($user->type == 3) {
            $data['org_id'] = $user->org_id;
        } else if ($user->type == 2) {
            $data['org_id'] = $user->team->org_id;
            $data['parent_id'] = $user->team_id;
        }
        $data['legal_person'] = '';
        $data['legal_person_id'] = '';
        $data['legal_person_phone'] = '';
        // default values;
        $data['parent_id'] = isset($data['parent_id']) ? $data['parent_id'] : 0;
        $data['user_id'] = 0;
        $data['reward_time'] = 0;
        $data['auth_create_team'] = 1;
        $data['auth_exempt_project'] = 0;
        $data['join_type'] = 1; // 允许任何人加入
        $data['verify_msg'] = '';
        $data['verify_status'] = '0';
        $data['photo'] = '';
        $data['identifier'] = '';
        $data['business_licence'] = isset($data['business_licence']) ? $data['business_licence'] : '';
        $data['logo'] = isset($data['logo']) ? $data['logo'] : '';
        $data['certificate_photo'] = isset($data['certificate_photo']) ? $data['certificate_photo'] : '';
        $data['team_photo'] = isset($data['team_photo']) ? $data['team_photo'] : '';
        $data['verify_status'] = '1';
        $data['slogan'] = isset($data['slogan']) ? $data['slogan'] : '';
        $data['auth_create_goods'] = 0;
        if (isset($data['acl'])) {
            $data['auth_exempt_project'] = strpos($data['acl'], "project-skip-verify") === false ? 0 : 1;
            $data['auth_create_team'] = strpos($data['acl'], "owner-subteam") === false ? 0 : 1;
            $data['auth_create_goods'] = strpos($data['acl'], "auth-create-goods") === false ? 0 : 1;
            // 拥有子团队的人，自动就有项目免审权
            if ($data['auth_create_team']) {
                $data['auth_exempt_project'] = 1;
            }
        }

        $node->fill($data);

        if ($node->save()) {

            if (isset($data['pwd'])) {
                $user = new User();
                $user->fill([
                    'username' => $data['username'],
                    'pwd' => bcrypt($data['pwd']),
                    'email' => isset($data['email']) ? $data['email'] : '',
                    'type' => 2,
                    'org_id' => $data['org_id'],
                    'team_id' => $node->id
                ]);
                $user->save();
                $node->fill([
                    'user_id' => $user->id
                ]);
                $node->save();
            }

            $node->syncServiceType();
            $node->syncServiceTarget();

            return $this->returnJSON(null, 0, '新增成功');
        }
        return $this->returnJSON(null, 500, '新建失败');
    }

    public function update(Request $request, $id)
    {
        $user = $request->user();
        $node = Team::findOrFail($id);
        $firstSave = $node->verify_status == -1;

        $this->validate($request, [
            'name' => ['required', 'max:32', Rule::unique('team')->where(function($query) use ($user, $id){
                if($user->type == 4 || $user->type == 5)
                {
                    $orgId = request()->input('org_id');
                }elseif($user->type == 3)
                {
                    $orgId = $user->org_id;
                }else{
                    $orgId = $user->team->org_id;
                }
                $query->where('org_id', $orgId)->where('id', '!=', $id);
            })],
            'type' => 'required|max:32',
            'service_target' => 'required|max:32',
            'contact_name' => 'required|max:32',
            'contact_phone' => 'required|max:32',
            'contact_email' => 'required|max:255|email',
            'address' => 'required',
//            'legal_person' => 'required|max:12',
//            'legal_person_id' => 'required|max:18',
//            'legal_person_phone' => 'required|max:32',
            'abstract' => 'required',
            'username' => [
                'max:64',
                Rule::unique('user')->where('type', 2)->ignore($node->user_id)
            ],
            'pwd' => 'max:64',
            'slogan' => 'max:20'
        ]);

        $data = $request->only([
            'org_id',
            'logo',
            'name',
            'type',
            'service_target',
            'contact_name',
            'contact_phone',
            'contact_email',
            'contact_addr',
//            'legal_person',
//            'legal_person_id',
//            'legal_person_phone',
            'certificate_photo',
            'team_photo',
            'abstract',
            'username',
            'pwd',
            'acl',
            'address',
            'slogan',
            'stars'
        ]);
//        dd($data);
        $data['legal_person'] = '';
        $data['legal_person_id'] = '';
        $data['legal_person_phone'] = '';
        $data['parent_id'] = intval($request->input('parent_id'));

        $data['logo'] = isset($data['logo']) ? $data['logo'] : '';
        $data['slogan'] = isset($data['slogan']) ? $data['slogan'] : '';
        $data['certificate_photo'] = isset($data['certificate_photo']) ? $data['certificate_photo'] : '';
        $data['team_photo'] = isset($data['team_photo']) ? $data['team_photo'] : '';

        if (isset($data['acl'])) {
            $data['auth_exempt_project'] = strpos($data['acl'], "project-skip-verify") === false ? 0 : 1;
            $data['auth_create_team'] = strpos($data['acl'], "owner-subteam") === false ? 0 : 1;

            // 拥有子团队的人，自动就有项目免审权
            if ($data['auth_create_team']) {
                $data['auth_exempt_project'] = 1;
            }
        }


        if (isset($data['pwd'])) {
            if ($node->user_id) {
                $user = User::findOrFail($node->user_id);
                $user->fill([
                    'username' => $data['username'],
                    'pwd' => bcrypt($data['pwd']),
                    'email' => isset($data['email']) ? $data['email'] : '',
                    'team_id' => $node->id
                ]);
                $user->save();
            } else {
                $user = new User();
                $user->fill([
                    'username' => $data['username'],
                    'pwd' => bcrypt($data['pwd']),
                    'email' => isset($data['email']) ? $data['email'] : '',
                    'type' => 3,
                    'team_id' => $node->id
                ]);
                $user->save();
                $data['user_id'] = $user->id;
            }
        }


        $node->fill($data);
        if ($node->save()) {

            $node->syncServiceType();
            $node->syncServiceTarget();

            return $this->returnJSON(null, 0, '保存成功');
        }
        return $this->returnJSON(null, 500, '保存失败');
    }

    public function destroy(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        if (Team::whereRaw('id IN (?)', [$ids])->delete()) {
            User::whereIn('team_id', $ids)->delete();
            return $this->returnJSON($ids, 0, '删除成功');
        } else {
            return $this->returnJSON(null, 1, "删除失败");
        }
    }

    public function blacklist(Request $request) {
        $perPage = $request->get('perPage', 10);
        $query = Team::query();
        $query->where('in_blacklist', '=', 1);
        $user = $request->user();
        if ($user->type == 4 && $request->has('org_id')) {
            $query = $query->where('org_id', '=', $request->get('org_id'));
        }
        if ($user->type == 2) {
            $subTeamIds = array_map(function($item) {
                return $item['id'];
            }, Team::whereDescendantOf($user->team)->select('id')->where('org_id',$user->team->org_id)->get()->toArray());
            $query->whereIn('parent_id', $subTeamIds);
        } else if ($user->type == 3) {
            $query->where('org_id', '=', $user->org_id);
        }

        $info = $query->paginate($perPage)->toArray();

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function unblack(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = Team::whereIn('id',  $ids)->update(['in_blacklist' => 0]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            return $this->returnJSON($ids, 0, '移除黑名单成功');
        } else {
            return $this->returnJSON(null, 1, "移除黑名单失败");
        }
    }
    public function black(Request $request, $id)
    {
        $this->validate($request, [
            'reason' => 'required'
        ]);

        $now = new Carbon();

        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = Team::whereIn('id',  $ids)->update([
            'in_blacklist' => 1,
            'black_reason' => $request->get('reason'),
            'blacked_at' => $now->toDateTimeString()
        ]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            return $this->returnJSON($ids, 0, '拉黑成功');
        } else {
            return $this->returnJSON(null, 1, "拉黑失败");
        }
    }


    public function verify(Request $request) {
        $perPage = $request->get('perPage', 10);
        $query = Team::query()->with('parentTeam', 'org');
        $user = $request->user();

//        $query->where('verify_status', '<>', '-1');
        if ($request->has('status')) {
            $query->where('verify_status', '=', $request->get('status'));
        }
        if ($request->has('org_id')) {
            $query = $query->where('org_id', '=', $request->get('org_id'));
        }

        if($user->type == 3)
        {
            $query->where('org_id', '=', $user->org_id);
        }

        if ($user->type == 2) {
//            $subTeamIds = array_map(function($item) {
//                return $item['id'];
//            }, Team::whereDescendantOf($user->team)->select('id')->get()->toArray());
//            $query->whereIn('parent_id', $subTeamIds);
            $query->where('parent_id', '=', $user->team_id);
        }


        $query->orderBy('updated_at', 'desc');

        $info = $query->paginate($perPage)->toArray();

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function accept(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = Team::whereIn('id',  $ids)->update(['verify_status' => 1]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {


            $sms = new \App\Libs\Sms();
            $teamList = Team::whereIn('id',  $ids)->get();
            foreach($teamList as $team)
            {
                $ret = $sms->sendTemplateSMS($team->contact_phone, array(),209756);


            }

            return $this->returnJSON($ids, 0, '审核通过');
        } else {
            return $this->returnJSON(null, 1, "操作失败");
        }
    }
    public function reject(Request $request, $id)
    {
        $this->validate($request, [
            'reason' => 'required'
        ]);

        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = Team::whereIn('id',  $ids)->update([
            'verify_status' => 2,
            'verify_msg' => $request->get('reason')
        ]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            $sms = new \App\Libs\Sms();
            $teamList = Team::whereIn('id',  $ids)->get();
            foreach($teamList as $team)
            {
                $ret = $sms->sendTemplateSMS($team->contact_phone, array($request->get('reason')),209757);
            }
            return $this->returnJSON($ids, 0, '驳回成功');
        } else {
            return $this->returnJSON(null, 1, "操作失败");
        }
    }

    public function getAcl(Request $request, $id) {
        $node = Team::findOrFail($id);
        $user = $request->user();
        $data = $node->toArray();

        $data['canEdit'] = 0;

        if (
            $user->type == 3
            || $user->type == 4
            || $user->type == 5
            || $user->type == 2 && $node->_lft > $user->team->_lft && $node->_rgt < $user->team->_rgt
        ) {
            $data['canEdit'] = 1;
        }

        $acl = [];

        if (isset($data['auth_exempt_project']) && intval($data['auth_exempt_project'])) {
            $acl[] = 'project-skip-verify';
        }

        if (isset($data['auth_create_team']) && intval($data['auth_create_team'])) {
            $acl[] = 'owner-subteam';
        }

        if (isset($data['auth_create_goods']) && intval($data['auth_create_goods'])) {
            $acl[] = 'auth-create-goods';
        }

        $data['acl'] = join(",", $acl);

        return $this->returnJSON($data, 0, 'ok');
    }

    public function saveAcl(Request $request, $id)
    {
        $node = Team::findOrFail($id);
        $user = $request->user();

        if (
            !(
                $user->type == 3
                || $user->type == 4
                || $user->type == 5
                || $user->type == 2 && $node->_lft > $user->team->_lft && $node->_rgt < $user->team->_rgt
            )
        ) {
            throw new \Exception('权限不够');
        }

        $data = $request->only([
            'auth_create_goods',
            'join_type',
            'acl'
        ]);

        $data['auth_create_team'] = isset($data['acl']) && strpos($data['acl'], "owner-subteam") !== false ? 1 : 0;
        $data['auth_exempt_project'] = isset($data['acl']) && strpos($data['acl'], "project-skip-verify") !== false ? 1 : 0;
        $data['auth_create_goods'] = isset($data['acl']) && strpos($data['acl'], "auth-create-goods") !== false ? 1 : 0;
//        dd($data);

        // 拥有子团队的人，自动就有项目免审权
        if ($data['auth_create_team']) {
            $data['auth_exempt_project'] = 1;
        }

        $node->fill($data);
        if ($node->save()) {

            $acl = [];

            if ($node->auth_exempt_project) {
                $acl[] = 'project-skip-verify';
            }

            if ($node->auth_create_team) {
                $acl[] = 'owner-subteam';
            }

            if ($node->auth_create_goods) {
                $acl[] = 'auth-create-goods';
            }

            return $this->returnJSON([
                'acl' => join(",", $acl)
            ], 0, '保存成功');
        }
        return $this->returnJSON(null, 500, '保存失败');
    }

    public function chained(Request $request, $id = 0) {
        $query = Team::query()->select('name', 'id');
        $id = intval($id);

        $user = $request->user();
        if ($id) {
            $query->where('parent_id', '=', $id);
        } else if ($user->type == 2) {
            $query->where('parent_id', '=', $user->team_id);
        } else  {
            $query->whereNull('parent_id');
        }

        if ($user->type == 3) {
            $query->where('org_id', '=', $user->org_id);
        } else if ($user->type == 2) {
            $query->where('_lft', '>', $user->team->_lft);
            $query->where('_rgt', '<', $user->team->_rgt);
        }

        $nodes = $query->get()->toArray();

        if (!count($nodes)) {
            return $this->returnJSON(null);
        }

        $options = array_map(function($node) {
            return [
                'value' => $node['id'],
                'label' => $node['name']
            ];
        }, $nodes);

        return $this->returnJSON([
            'options' => $options
        ]);
    }

    public function sug(Request $request) {
        $term = $request->get('term');
        $query = Team::query()->select('name', 'id');



        if (!empty($term)) {
            $query->where('name', 'like', '%'.$term.'%');
        }

        $query->where('verify_status', '=', 1);

//        if (!$request->has('do_not_filter_auth_create_team')) {
//            $query->where('auth_create_team', '=', 1);
//        }

        if ($request->has('auth_create_goods')) {
            $query = $query->where('auth_create_goods', '=', $request->get('auth_create_goods'));
        }

        $user = $request->user();
        $disabledIds = [];

        if (preg_match('#^api/team/term#', $request->path())) {
            if ($request->has('org_code')) {
                $hasIds = new Hashids('', 10);
                $org_id = $hasIds->decode($request->get('org_code'));
                $org = Org::find($org_id);

//                echo $hasIds->encode('2');exit;

                if (!$org) {
                    throw new \Exception("非法调用");
                }

                $query->where('org_id', '=', $org_id);
            } else {
                throw new \Exception("非法调用");
            }
        } else {
            if ($user && $user->type == 4 || $user->type == 5 && $request->has('org_id')) {
                $query->where('org_id', '=', $request->get('org_id'));
            } else if ($user && $user->type == 3) {
                $query->where('org_id', '=', $user->org_id);
            } else if ($user && $user->type == 2) {
                $query->where('org_id', '=', $user->team->org_id);
                $query->where('_lft', '>', $user->team->_lft);
                $query->where('_rgt', '<', $user->team->_rgt);
            }

            if ($request->has('id')) {
                $team = Team::findOrFail($request->get('id'));
                $disabledIds = $team->descendants()->pluck('id')->toArray();
                $disabledIds[] = $team->id;
            }
        }

//        Log::info($query->toSql());
//        Log::info($query->getBindings());
        $nodes = $query->get()->toArray();

        $options = array_map(function($node) use ($disabledIds) {
            return [
                'value' => $node['id'],
                'label' => $node['name'],
                'disabled' => in_array($node['id'], $disabledIds)
            ];
        }, $nodes);

        return $this->returnJSON($options);
    }

    public function notify(Request $request, $teamIds=null){
        $user = $request->user();
        if($teamIds!=null) {
            $teamIds = explode(',', $teamIds);
            $users = User::whereIn('team_id', $teamIds)->where('type', '=', '2')->select('id')->get()->toArray();
            $data = array_map(function ($item) use($user, $request) {

                //微信模版消息，站内信
                WechatTempMsg::add(55, ['user_id'=>$item['id']]);
                return array('from_user_id'=>$user->id,
                    'to_user_id' => $item['id'],
                    'title' => $request->get('title', ''),
                    'type' => 1,
                    'content' => $request->get('content', ''));
            }, $users);
            DB::table('user_message')->insert($data);
        }else{

            $query = Team::query();
            $query->where('verify_status', '=', 1);
            $query->where('in_blacklist', '=', 0);

            if ($user->type == 4 || $user->type == 5) {

            } else if ($user->type == 3) {
                $query->where('org_id', '=', $user->org_id);

            } else if ($user->type == 2) {
                $team = $user->team;

                $teamIds = array_map(function($item) {
                    return $item['id'];
                }, Team::whereDescendantOrSelf($team)->select('id')->where('org_id',$team->org_id)->get()->toArray());

                $query->whereIn('parent_id', $teamIds);
            } else {
                throw new \Exception('权限不足');
            }

            $teamIds = array_map(function($item) {return $item['id'];}, $query->select('id')->get()->toArray());


            $users = User::whereIn('team_id', $teamIds)->where('type', '=', '2')->select('id')->get()->toArray();
            $data = array_map(function ($item) use($user, $request) {
                //微信模版消息，站内信
                WechatTempMsg::add(55, ['user_id'=>$item['id']]);

                return array('from_user_id'=>$user->id,
                    'to_user_id' => $item['id'],
                    'title' => $request->get('title', ''),
                    'type' => 0,
                    'content' => $request->get('content', ''));
            }, $users);
            DB::table('user_message')->insert($data);
        }
        return $this->returnJSON(null, 0, '发送成功');
    }

    public function bindWechat(Request $request)
    {
        $user = $request->user();

        if($user->type != 2)
        {
            throw new \Exception('权限不足');
        }


        $orgInfo = Org::find($user->org_id);

        $url = 'http://'.$orgInfo->wechat_app_id.env('BASE_HOST', '.alpha.flashdiet.cn');

        $path = '/bindwechat?user_id='.$user->id;

        $data = $url.$path;

        $image = QrCode::format('png')->size($request->get('size', 300))/*->merge('/storage/logo.png')*/->generate($data);
        return response($image)->header('Content-type','image/png');
    }

    public function unbindWechat(Request $request) {
        $user = $request->user();

        if($user->type != 2)
        {
            throw new \Exception('权限不足');
        }
        $query = User::findOrFail($user->id);
        $query->fill([
            'open_id' => '',
        ]);
        $query->save();
//        dd($query);
        return $this->returnJSON(null, 0, '解绑成功');
    }

    public function starCertificateAccept(Request $request, $id) {

        $ids = array_map(function($item){
            return intval($item);
        },explode(',', $id));
//        DB::raw('update volunteer set volunteer.stars=volunteer.stars_verify_num, volunteer.stars_verify_status=1')->whereIn('volunteer.id', $ids);
        Team::whereIn('id', $ids)->update([
            'stars' => DB::raw('stars_verify_num'),
            'stars_verify_status' => 1,
        ]);
//        Volunteer::whereIn('id', $ids)->updateRaw();
        return $this->returnJSON($ids, 0, "修改成功");
    }

    public function starCertificateReject(Request $request, $id) {
//        $this->validate($request, [
//
//        ]);

        $ids = array_map(function($item){
            return intval($item);
        },explode(',', $id));

        Team::whereIn('id', $ids)->update([
            'stars_verify_status' => 2
        ]);

        return $this->returnJSON($ids, 0, "修改成功");
    }

    public function authGoods(Request $request){

//        $pageNum = request()->input('current_page', 1);
        $perPage = $request->get('perPage', 10);

        $user = $request->user();
        if ($user->type == 2) {
            return $this->returnJSON('', 10001, "权限不足");
        }
        $data = Team::with('org')->where('auth_create_goods',1);
        $org_id = $request->get('org_id', 0);
        if($user->type == 3){
            $org_id = $user->org_id;
        }

        if ($org_id) {
            $data = $data->where('org_id', $org_id);
        }


//        $count = $data->count();
//        $from = ($pageNum - 1)*$pageSize;
//        $data = $data->take($pageSize)->skip($from)->get();
//        $data = $data->get();
        $data = $data->paginate($perPage)->toArray();
        $info = $data['data'];

        for ($i = 0; $i < count($info); $i++){
            $info[$i]['goods_num'] = Goods::where('team_id',$info[$i]['id'])->count();
            $info[$i]['orders_num'] = Order::where('team_id',$info[$i]['id'])->count();
            $info[$i]['orders_points'] = Order::where('team_id',$info[$i]['id'])->sum('points');

        }
        $data['data'] = $info;
//        $pageInfo = [
//            "current_page" => intval($pageNum),
//            "total_page" => ceil($count / $pageSize),
//            "page_size" => intval($pageSize)
//        ];

//        $info = $data->paginate($perPage)->toArray();

        return $this->returnJSON([
            'count' => $data['total'],
            'rows' => $data['data']
        ]);
    }

    public function deleteAuthGoods(Request $request)
    {
        $user = $request->user();
        $team_id = $request->input('id');

        $data = Team::where('id',$team_id)->where('org_id',$user->org_id)->first();
        if(empty($data)){
            return $this->returnJSON(null, 10002, '未找到此团队');
        }
        $data->auth_create_goods = 0;
        if($data->save()){
            return $this->returnJSON(null, 0, '删除成功');
        }
    }

}
